# -*- coding:utf-8 -*-

# @File     :users
# @Author   :Yupeng
# @Date     :2018/10/24 18:40

from enum import Enum
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_noop as _, ugettext
from .users import User


class NotificationType(Enum):
    '''

    '''
    EMAIL_NEEDS_VERIFYING = 1, _("A confirmation email has been sent to your email address: %(object1)s, please click the link in it to verify your account.")
    NEW_TICKET_REPLY_FROM_ADMIN = 2, _("Your ticket %(object1)s has a new reply.")
    NEW_TICKET_FROM_USER = 3, _("%(object1)s has opened a new ticket %(object2)s.")
    NEW_TICKET_REPLY_FROM_USER = 4, _("Ticket %(object1)s has a new reply from %(object2)s.")
    TICKET_CLOSED = 5, _("Admin closed your ticket %(object1)s.")
    TASK_SUCCEED = 6, _('Your task \"%(object1)s\" has been done.')
    TASK_FAILED = 7, _('Your task \"%(object1)s\" failed... :(')


class Notification(models.Model):
    class Meta:
        ordering = ('-timestamp',)

    recipient = models.ForeignKey(User, related_name='notification', on_delete=models.CASCADE)
    unread = models.BooleanField(default=True)
    timestamp = models.DateTimeField(auto_now=True)
    notification_type = models.IntegerField()
    object1 = models.CharField(max_length=254, null=True, blank=True)
    object2 = models.CharField(max_length=254, null=True, blank=True)
    object3 = models.CharField(max_length=254, null=True, blank=True)

    def to_string(self):
        return ugettext(_notification_map[self.notification_type]) % {'object1': self.object1,
                                                                      'object2': self.object2,
                                                                      'object3': self.object3}

    def __unicode__(self):
        return self.to_string()

    def __repr__(self):
        return self.to_string()

    def to_dict(self):
        return {'id': self.pk,
                'unread': self.unread,
                'timestamp': self.timestamp,
                'content': self.to_string()}


_notification_map = dict([x.value for x in NotificationType])


class SystemNotification(models.Model):
    title = models.CharField(max_length=254)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    _newest = None

    @staticmethod  # 静态方法，类不需要实例化就可以调用该方法
    def newest_notification():
        if not SystemNotification._newest:
            SystemNotification._newest = SystemNotification.objects.order_by('-id').first()
        return SystemNotification._newest

    def save(self, *args, **kwargs):
        if not self.id:
            SystemNotification._newest = self
        super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        if SystemNotification._newest and SystemNotification._newest.id == self.id:
            SystemNotification._newest = None
        super().delete(*args, **kwargs)
